# Create your views here.
from rest_framework.decorators import api_view
from django.http import JsonResponse
import json
from .download import down
from .upload import  upload_file
from .pdfexcel import pdf_exccel2
def check_error(content, key):
    if content is None:
        return JsonResponse({"message": "Invalid JSON data"}, status=400)
def check_pdfexcel(content, key):
    if "转化超时间" in content:
        return JsonResponse({"message": key}, status=400)
@api_view(['POST'])
def upload(request):
    print("请求体为：",request.body)  # 打印原始的请求体
    if request.content_type == 'application/json':
        try:
            data = json.loads(request.body.decode('utf-8'))
            url = data.get('url')
            print("解析的文件地址 ： ", url)
            saveFileUrl=down(url)
            check_error(saveFileUrl,"文件下载失败！！")
            print("文件下载地址为：",saveFileUrl)

            excelUrl=pdf_exccel2(saveFileUrl,i=1)
            print("流水pdf转换后excel文件123",excelUrl)
            check_pdfexcel(excelUrl,"文件转换失败！！")
            print("流水pdf转换后excel文件456",excelUrl)

            upload_file_url=upload_file(excelUrl)
            check_error(upload_file_url,"文件上传失败！！")
            print("上传的地址为：",upload_file_url)
            return JsonResponse({"code":200,"msg":"执行成功","url": upload_file_url})
        except json.JSONDecodeError:
            return JsonResponse({"message": "Invalid JSON data"}, status=400)
    else:
            return JsonResponse({"message": "Invalid Content-Type"}, status=400)